import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  message,
  Modal,
} from 'antd';
import { articleApi, DeleApi } from 'api/article';

import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom/cjs/react-router-dom.min';
import Errosrc from '../../assets/error.png';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import Channel from 'pages/component/channel';

const { RangePicker } = DatePicker;
// 声明一个函数

// 挂载并// 调用数据
// 声明一个state保存数据
// 渲染要渲染的列表

export default function ArticleList() {
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];

  const [articleData, setArticleData] = useState({});

  const loadArticles = async (params) => {
    const res = await articleApi(params);
    console.log('res 11 ----->  ', res);
    setArticleData(res.data);
  };
  const formDataRef = useRef(null);
  const pageInfoRef = useRef(null);
  const handleChange = (page, pageSize) => {
    pageInfoRef.current = { page, per_page: pageSize };
    loadArticles({ page, per_page: pageSize, ...(formDataRef.current || {}) });
  };
  const handleDele = async (id) => {
    Modal.confirm({
      title: '温馨提示',
      content: '你确定要删除这篇文章？',
      // 2. onOk改为异步函数
      onOk: async () => {
        await DeleApi(id);
        const formData = formDataRef.current || {};
        const pageInfoData = pageInfoRef.current || {};
        loadArticles({ ...formData, ...pageInfoData });
        message.success('删除成功', 1);
      },
    });
  };
  // 挂载后发请求获取数据
  useEffect(() => {
    loadArticles();
  }, []);

  const handleSubmit = (values) => {
    console.log('123  ----->  ', values);
    let formData = { ...values };
    //   1. 转换status字段的数据
    if (values.status === -1) {
      // delete删除对象的某个键
      delete formData.status;
    }

    if (values.date) {
      const startTime = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const endTime = values.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
      formData.begin_pubdate = startTime;
      formData.end_pubdate = endTime;
      delete formData.date;
    }

    // 2. 转换date字段的数据
    // 3. 验证数据
    console.log('formData  ----->  ', formData);
    formDataRef.current = formData;
    loadArticles(formData);
  };
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (value) => {
        if (!value.images.length) {
          return <img width={150} src={Errosrc} alt="" />;
        }
        return <img width={150} src={value.images[0]} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        const inform = articleStatus.find((item) => item.id === value);
        return <Tag color={inform.color}>{inform.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    { title: '评论数', dataIndex: 'comment_count' },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: 'Action',
      key: 'action',
      render: (value, record, index) => {
        return (
          <>
            <Button
              shape="circle"
              type="primary"
              icon={<EditOutlined />}
            ></Button>
            <Button
              shape="circle"
              type="primary"
              icon={<DeleteOutlined />}
              onClick={() => handleDele(record.id)}
            ></Button>
          </>
        );
      },
    },
  ];

  return (
    <div>
      <Card style={{ paddingTop: 24 }}>
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/home">首页</Link>
          </Breadcrumb.Item>

          <Breadcrumb.Item>文章发表</Breadcrumb.Item>
        </Breadcrumb>
        <Form
          autoComplete="off"
          onFinish={handleSubmit}
          initialValues={{ status: -1, channels_id: 0 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channels_id">
            <Channel></Channel>
          </Form.Item>
          <Form.Item name="date" label="日期">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
        筛选总条数的结果 {articleData.total_count}
        <Table
          columns={columns}
          dataSource={articleData.results}
          rowKey="id"
          pagination={{
            onChange: handleChange,
            position: ['bottomCenter'],
            current: articleData.page,
            pageSize: articleData.per_page,
            total: articleData.total_count,
          }}
        />
      </Card>
    </div>
  );
}
